//
//  MTChatRoomLSingleView.swift
//  MT
//
//  Created by ooops on 2020/5/7.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

protocol MTChatRoomLSingleViewDelegate: NSObjectProtocol {
    func didTapEntranceChatRoom()
}

class MTChatRoomLSingleView: UIView {
    
    weak var delegate: MTChatRoomLSingleViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        makeConstraint()
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(chatRoomEntrance))
        addGestureRecognizer(tap)
    }
    
    @objc private func chatRoomEntrance() {
        self.delegate?.didTapEntranceChatRoom()
    }
    
    private func setupUI() {
        //contentView.addSubview(avatorGroupView)
        addSubview(avatorImageView)
        addSubview(clubNameLabel)
        addSubview(clubMessageLabel)
//        addSubview(clubAreaAndTotalLabel)
//        addSubview(joinClubButton)
        addSubview(lineView)
        
        //addSubview(noHistoryMessageLabel)
    }
    
    var lastMessage: JMSGMessage? {
        didSet {
           if lastMessage == nil {
                //noHistoryMessageLabel.isHidden = false
                clubNameLabel.isHidden = false
                clubNameLabel.text = "官方.觅颜官方账号"
                clubMessageLabel.isHidden = false
                clubMessageLabel.text = "暂无消息"
                return
           }
            //noHistoryMessageLabel.isHidden = true
            clubNameLabel.isHidden = false
            clubMessageLabel.isHidden = false
            clubNameLabel.text = "官方.觅颜官方账号"
            bindData(message: lastMessage!)
        }
    }
    
    var conversation: JMSGConversation? {
        didSet {
            /// 如果没有历史消息
            guard let lastMessage = lastMessage else {
                clubNameLabel.text = "官方.觅颜官方账号"
                clubMessageLabel.text = "暂无消息"
                return
            }
            /// 消息类型提示
            if let con = conversation, let messageType: JMSGContentType = lastMessage.contentType {
                let isGroup = con.ex.isChatRoom
                let prefix = (lastMessage.fromUser.isEqual(to: JMSGUser.myInfo()) == false) ? lastMessage.fromUser.displayName() + ":" : ""
                if messageType == .custom {
                    let content: JMSGCustomContent = lastMessage.content as! JMSGCustomContent
                    switch content.customMsgType() {
                    case .gift:
                        clubMessageLabel.text = prefix + "[礼物]"
                    case .redpack:
                        var msgText = "", conversationTypeString = ""
                        if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any>, lastMessage.fromUser.isEqual(to: JMSGUser.myInfo()) == false {
                            if let conversationType: Int = dict["targetType"] as? Int {
                                conversationTypeString = conversationType == 1 ? "向你撒了" : conversationType == 2 ? "往俱乐部里撒了" : "往广场撒了"
                            }
                            if let redpackC: Int = dict["money"] as? Int {
                                
                                let unredCount: String = con.unreadCount?.intValue ?? 0 > 1 ? "[\(con.unreadCount!.stringValue)条]" : ""
                                
                                if isGroup {
                                    let fromUser = lastMessage.fromUser
                                    if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                                        lastMessage.contentType != .eventNotification &&
                                        lastMessage.contentType != .prompt {
                                        msgText = "\(unredCount)\(lastMessage.fromUser.displayName())\(conversationTypeString)\(redpackC)钻石"
                                    }
                                } else {
                                    msgText = "\(conversationTypeString)\(redpackC)钻石"
                                }
                                
                                clubMessageLabel.text = msgText
                                //clubMessageLabel.textColor = UIColor.text.xfed600
                                clubMessageLabel.textColor = UIColor.text.x999999
                            }
                            
                        } else {
                            clubMessageLabel.text = prefix + "[红包]"
                        }
                    case .pullNotify:
                        if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                            if let senderUserName: String = infos["senderUserName"] as? String,
                                let pullNickname: String = infos["pullNickname"] as? String,
                                let senderNickname: String = infos["senderNickname"] as? String {
                                
                                let isSelf: Bool = (senderUserName == JMSGUser.myInfo().username)
                                /// 如果是自己发的红包
                                if isSelf {
                                    if let pullUserName = infos["pullUserName"] as? String {
                                        /// 自己领取了自己发的红包
                                        if senderUserName == pullUserName {
                                            clubMessageLabel.text = "你领取了自己发的红包"
                                            clubMessageLabel.textColor = UIColor.text.x999999
                                        } else {
                                            clubMessageLabel.text = "\(pullNickname)领取了你的红包"
                                            clubMessageLabel.textColor = UIColor.text.x999999
                                        }
                                    } else {
                                       clubMessageLabel.text = "\(pullNickname)领取了你的红包"
                                        clubMessageLabel.textColor = UIColor.text.x999999
                                    }
                                } else {
                                   /// 不是自己发的红包
                                   if let pullUserName = infos["pullUserName"] as? String {
                                       /// 是自己领取的
                                       if JMSGUser.myInfo().username == pullUserName {
                                           clubMessageLabel.text = " 你领取了\(senderNickname)的红包"
                                           clubMessageLabel.textColor = UIColor.text.x999999
                                       } else {
                                           clubMessageLabel.text = "\(pullNickname)领取了\(senderNickname)的红包"
                                           clubMessageLabel.textColor = UIColor.text.x999999
                                       }
                                   }
                               }
                            }
                        }
                    case .task:
                    if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                        clubMessageLabel.textColor = UIColor.text.x999999
                        if let name = infos["partyName"] as? String, let money = infos["partyGiftNum"] {
                            clubMessageLabel.text = "[" + name + "] 聚会任务"
                        }
                    }
                    default:
                        break
                    }
                } else {
                    switch messageType {
                    case .image:
                        clubMessageLabel.text = prefix + "[图片]"
                    case .text:
                        let infomation = con.latestMessageContentText()
                        clubMessageLabel.text = prefix + infomation.trim(trimNewline: true)
                    default:
                        let infomation = con.latestMessageContentText()
                        clubMessageLabel.text = prefix + infomation.trim(trimNewline: true)
                    }
                    clubMessageLabel.textColor = UIColor.text.x999999
                }
            }
        }
    }
    
    private func bindData(message: JMSGMessage) {
        let messageType: JMSGContentType = message.contentType
        if messageType == .custom {
            let content: JMSGCustomContent = message.content as! JMSGCustomContent
            switch content.customMsgType() {
            case .redpack:
                var msgText = "", conversationTypeString = ""
                if let dict : Dictionary<String, Any> = content.extras as? Dictionary<String, Any>, message.fromUser.isEqual(to: JMSGUser.myInfo()) == false {
                    if let conversationType: Int = dict["targetType"] as? Int {
                        conversationTypeString = conversationType == 1 ? "向你撒了" : conversationType == 2 ? "往俱乐部里撒了" : "往广场撒了"
                    }
                    if let redpackC: Int = dict["money"] as? Int {
                        
                        //let unredCount: String = con.unreadCount?.intValue ?? 0 > 1 ? "[\(con.unreadCount!.stringValue)条]" : ""
                        
                        //if isGroup {
//                        if let latestMessage = message {
                        let fromUser = message.fromUser
                        if !fromUser.isEqual(to: JMSGUser.myInfo()) &&
                            message.contentType != .eventNotification &&
                            message.contentType != .prompt {
                            msgText = "\(message.fromUser.displayName())\(conversationTypeString)\(redpackC)钻石"
                        }
//                        }
//                        } else {
//                            msgText = "\(conversationTypeString)\(redpackC)钻石"
//                        }
                        
                        clubMessageLabel.text = msgText
                        //clubMessageLabel.textColor = UIColor.text.xfed600
                        clubMessageLabel.textColor = UIColor.text.x999999
                    }
                    
                } else {
                    clubMessageLabel.text = "[红包]"
                }
            case .pullNotify:
                if let infos : Dictionary<String, Any> = content.extras as? Dictionary<String, Any> {
                    if let senderUserName: String = infos["senderUserName"] as? String,
                        let pullNickname: String = infos["pullNickname"] as? String,
                        let senderNickname: String = infos["senderNickname"] as? String {
                        
                        let isSelf: Bool = (senderUserName == JMSGUser.myInfo().username)
                        /// 如果是自己发的红包
                        if isSelf {
                            if let pullUserName = infos["pullUserName"] as? String {
                                /// 自己领取了自己发的红包
                                if senderUserName == pullUserName {
                                    clubMessageLabel.text = "你领取了自己发的红包"
                                    clubMessageLabel.textColor = UIColor.text.x999999
                                } else {
                                    clubMessageLabel.text = "\(pullNickname)领取了你的红包"
                                    clubMessageLabel.textColor = UIColor.text.x999999
                                }
                            } else {
                               clubMessageLabel.text = "\(pullNickname)领取了你的红包"
                                clubMessageLabel.textColor = UIColor.text.x999999
                            }
                        } else {
                           /// 不是自己发的红包
                           if let pullUserName = infos["pullUserName"] as? String {
                               /// 是自己领取的
                               if JMSGUser.myInfo().username == pullUserName {
                                   clubMessageLabel.text = " 你领取了\(senderNickname)的红包"
                                   clubMessageLabel.textColor = UIColor.text.x999999
                               } else {
                                   clubMessageLabel.text = "\(pullNickname)领取了\(senderNickname)的红包"
                                   clubMessageLabel.textColor = UIColor.text.x999999
                               }
                           }
                       }
                    }
                }
            default:
                break
            }
        } else {
//            let infomation = message.content.
//            clubMessageLabel.text = infomation.trim(trimNewline: true)
            switch messageType {
            case .text:
                if let textMessage: JMSGTextContent = message.content as? JMSGTextContent {
                    clubMessageLabel.text = textMessage.text.trim(trimNewline: true)
                }
            default:
                break
            }
            clubMessageLabel.textColor = UIColor.text.x999999
        }
    }
    
    private func makeConstraint() {
        avatorImageView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(44)
        }
        
        clubNameLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.snp.centerY).offset(-2)
            make.left.equalTo(avatorImageView.snp.right).offset(10)
            make.right.equalTo(self).offset(-16)
            make.height.equalTo(20)
        }
        
        clubMessageLabel.snp.makeConstraints { (make) in
            make.height.left.right.equalTo(clubNameLabel)
            make.top.equalTo(self.snp.centerY).offset(2)
            make.right.equalTo(self).offset(-24)
        }
        
//        clubAreaAndTotalLabel.snp.makeConstraints { (make) in
//            make.centerY.equalToSuperview()
//            make.right.equalTo(joinClubButton.snp.left).offset(-5)
//        }
        
//        joinClubButton.snp.makeConstraints { (make) in
//            make.centerY.equalToSuperview()
//            make.right.equalToSuperview().offset(-16)
//            make.width.equalTo(51)
//            make.height.equalTo(31)
//        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
//        noHistoryMessageLabel.snp.makeConstraints { (make) in
//            make.centerY.equalToSuperview()
//            make.left.equalTo(avatorImageView.snp.right).offset(10)
//            make.right.equalToSuperview().offset(-10)
//        }
    }
    
    /// 图片组
//    lazy var avatorGroupView: MTClubAvatorGroupView = {
//        let v = MTClubAvatorGroupView(frame: .zero, imgList: nil)
//        return v
//    }()
//    lazy var noHistoryMessageLabel: UILabel = {
//        let l = UILabel()
//        l.font = PingFangSCSemiboldFont(14)
//        l.textColor = UIColor.text.x161616
//        l.isHidden = true
//        l.text = "暂无历史消息"
//        return l
//    }()
    
    lazy var avatorImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
        imageV.layer.masksToBounds = true
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        imageV.image = UIImage(named: "Icon-60")
        return imageV
    }()
    
    lazy var clubNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = ""
        return l
    }()
    
    lazy var clubMessageLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = ""
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
//    lazy var clubAreaAndTotalLabel: UILabel = {
//        let l = UILabel()
//        l.font = PingFangSCRegularFont(12)
//        l.textColor = UIColor.redpack.x5d5d5d
//        l.text = ""
//        l.setContentHuggingPriority(.defaultLow, for: .horizontal)
//        l.textAlignment = .right
//        return l
//    }()
    
//    lazy var joinClubButton: UIButton = {
//        let btn = UIButton(type: .custom)
//        btn.setTitle("加入", for: .normal)
//        btn.addTarget(self, action: #selector(joinClub), for: .touchUpInside)
//        btn.setTitleColor(.black, for: .normal)
//        btn.backgroundColor = UIColor.theme.main
//        btn.titleLabel?.font = PingFangSCRegularFont(14)
//        btn.layer.cornerRadius = 3
//        btn.layer.masksToBounds = true
//        return btn
//    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }


}
